<script setup>
import { watch, ref } from 'vue'
import powerSet from './power-set'
import { defineEmits } from 'vue'

const emit = defineEmits('sendData')


const props = defineProps({
  goods: Object
})
let pathMap = ref({})
// const getGoods = async () => {
//   // 1135076  初始化就有无库存的规格
//   // 1369155859933827074 更新之后有无库存项（蓝色-20cm-中国）
//   const res = await axios.get('http://pcapi-xiaotuxian-front-devtest.itheima.net/goods?id=1369155859933827074')
//   // console.log(res)
//   goods.value = res.data.result
//   console.log(goods.value)
// }

//生成有效路径字典对象
const getPathMap = (goods) => {
  const pathMapTwo = {}
  // console.log(goods, 'hello')
  //1.根据skus字段生成有效的sku数组
  const effectSkus = goods.skus.filter((item) => item.inventory > 0)
  // console.log(effectSkus)
  // 2.根据有效的sku使用求子集算法
  effectSkus.forEach(sku => {
    // 2.1获取匹配的valueName组成的数组
    const selectedValArr = sku.specs.map(val => val.valueName)
  // console.log(selectedValArr)
  //2.2使用算法获取子集
  //  console.log(powerSet(selectedValArr))
  const valueArrPowerSet = powerSet(selectedValArr)
  // console.log(valueArrPowerSet, sku.id)
  //3.把得到的子集生成最终的路径字典对象
  valueArrPowerSet.forEach(arr => {
    //使用数组的join方法得到key
    const key = arr.join('-')
    //已经存在key就直接往数组中添加skuId，没有的话做赋值操作
      if(pathMapTwo[key]) {
        pathMapTwo[key].push(sku.id)//同一个有效规格的子集肯定是不一样的
      }
      else{
        pathMapTwo[key] = [sku.id]
      }
  })
  })
  return pathMapTwo  
}
// getPathMap(goods.value)


//初始化禁用状态
const initDisabledStatus = (specs) => {
  specs.forEach(item => {
    item.values.forEach(element => {
      if(!pathMap.value[element.name]) {
        element.disabled = true//表示禁用
      }
      else{
        element.disabled = false
      }
    })
  })
}


//将函数位置提前，确保在访问函数时已经定义了函数
watch(() => props.goods, (newVal) => {
  if(newVal) {
    // console.log(newVal, 'newVal')
    // console.log(newVal.value, 'newVal_value')
    pathMap.value = getPathMap(newVal)
    // console.log(pathMap.value, 'pathMap.value')
    initDisabledStatus(newVal.specs)
  }
}, {immediate: true, deep: true})


//点击更新激活状态
const changeSelectedStatus = (item, val) => {
  if(val.disabled) {
    return
  }
  // console.log(val)
  // val里面本来是没有selected这个属性的，这样第一次会走else添加属性  
  if(val.selected) {
    val.selected = false
  }
  else{
    item.values.forEach((element) => {
      element.selected = false
    })
    val.selected = true
  }
  // const selectedArr = getSelectedValues(goods.value.specs)
  // console.log(selectedArr)
  // console.log(val)
  updateDisabledStatus(props.goods.specs)
  //产出数据
  //不是用props.goods.value.specs而是用props.goods.specs
  const selectedArr = getSelectedValues(props.goods.specs)
  // console.log(selectedArr, 'selectedArr')
  if(selectedArr.findIndex((item) => item === undefined) === -1)  {
    const key = selectedArr.join('-')
    // console.log(key, 'key')
    // console.log(pathMap.value[key], 'object-key')

    const skuId = pathMap.value[key]
    // console.log(skuId, 'skuId')
    // console.log(skuId[0])
    // console.log(goods.value.skus)
    if(skuId) {
      const skuIndex = props.goods.skus.findIndex(item => item.id === skuId[0])
      emit('sendData', props.goods.skus[skuIndex])
      console.log(props.goods.skus[skuIndex], '最终得到的sku对象')
    }
    // console.log(skuIndex)
    // console.log(props.goods.skus[skuIndex])
  }
}



//获取选中项的匹配数组
const getSelectedValues = (specs) => {
  const arr = []
  specs.forEach(spec => {
    const selectedVal = spec.values.find(item => item.selected)
    // console.log(selectedVal)
    arr.push(selectedVal ? selectedVal.name : undefined)
  })
  // console.log(arr)
  return arr
}

//切换时更新禁用状态

// 更新updateDisabledStatus中的key生成
const updateDisabledStatus = (specs) => {
  specs.forEach((spec, index) => {
    //这里spec是每一行，index代表在行号
    const selectedValues = getSelectedValues(props.goods.specs)
    //相当于按行进行替换，每次替换的时候其他行都是用selectedValues中的值，然后本行用val中的name进行替换
    spec.values.forEach(val => {
      selectedValues[index] = val.name
      const key = selectedValues.filter(value => value).join('-')
      // console.log(key)
      // console.log(val)
      //相当于遍历的时候就将val拼接到了已经得到的selectedValues数组中，这时就可以根据拼接结果有没有进行禁用或者不禁用的设计
      // if(pathMap.value[key]) {
      //   val.disabled = false
      // }
      // else{
      //   val.disabled = true
      // }
      val.disabled = !pathMap.value[key]
      // console.log(val)
    })
  })
}
</script>

<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name">
          <!-- 图片类型规格 -->
          <img v-if="val.picture" :class="{selected: val.selected, disabled: val.disabled}" @click="$event => changeSelectedStatus(item, val)" :src="val.picture" :title="val.name">
          <!-- 文字类型规格 -->
          <span v-else :class="{selected: val.selected, disabled: val.disabled}" @click="$event => changeSelectedStatus(item, val)">{{ val.name }}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>

<style scoped lang="scss">
@mixin sku-state-mixin {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;

  &.selected {
    border-color: #27ba9b;
  }

  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}

.goods-sku {
  padding-left: 10px;
  padding-top: 20px;

  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;

    dt {
      width: 50px;
      color: #999;
    }

    dd {
      flex: 1;
      color: #666;

      >img {
        width: 50px;
        height: 50px;
        margin-bottom: 4px;
        @include sku-state-mixin;
      }

      >span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        margin-bottom: 4px;
        @include sku-state-mixin;
      }
    }
  }
}
</style>